<template>
  <div class="TeachingPlan">
    <div class="TeachingPlanTop">

      <!-- <div class="info"> -->
      <div class="planName">
        <p class="planNameText">计划名称：</p>
        <el-input
          v-model="planNameValue"
          placeholder="请输入课程名称"
        ></el-input>
      </div>
      <div class="school">
        <p>所属院校：</p>
        <el-select
          v-model="saveForm.upResId"
          clearable
          placeholder="请选择"
          @clear="handleClear"
          ref="selectUpResId"
        >
          <!-- // 设置一个隐藏的下拉选项
      // 如果不设置一个下拉选项，下面的树形组件将无法正常使用 -->
          <el-option hidden :value="saveForm.upResId" :label="upResName">
          </el-option>
          <!-- // 设置树形组件
        是否在点击节点的时候展开或者收缩节点， 默认值为 true，如果为 false，则只有点箭头图标的时候才会展开或者收缩节点。
        // 是否在点击节点的时候选中节点，默认值为 false，即只有在点击复选框时才会选中节点。
          // 节点被点击时的回调 -->
          <el-tree
            :data="data"
            :props="defaultProps"
            :expand-on-click-node="false"
            :check-on-click-node="true"
            @node-click="handleNodeClick"
          >
          </el-tree>
        </el-select>
      </div>
      <div class="major">
        <p>所属专业：</p>
        <el-select v-model="majorValue" placeholder="请选择所属专业">
          <el-option
            v-for="item in majorOptions"
            :key="item.majorId"
            :label="item.majorName"
            :value="item.majorId"
          >
          </el-option>
        </el-select>
      </div>
      <div class="moreBtn">
        <el-button
          type="primary"
          @click="searchBtn"
          class="searchBtn"
          icon="el-icon-search"
          >搜索</el-button
        >
        <el-button
          type="primary"
          @click="refreshBtn"
          class="refreshBtn"
          icon="el-icon-refresh"
          >重置</el-button
        >
      </div>
      <!-- </div> -->
    </div>
    <div class="TeachingPlanBottom">
      <!-- <div class="infoTeachingPlanBottom"> -->
        <div class="operationBtns">
          <div class="setBtnsLeftTitle">
            <p>管理列表</p>
          </div>
          <div class="setBtns">
            <el-button type="primary" class="newAdd" @click="addCollege">
              <i class="el-icon-plus"></i>
              新增
            </el-button>
            <el-button type="primary" class="moreDelete" @click="moreDelete">
              <i class="el-icon-close"></i>
              批量删除
            </el-button>
            <el-button
              type="primary"
              class="moreRelease"
              @click="batchRelease"
            >
              <i class="el-icon-s-promotion"></i>
              批量发布
            </el-button>
            <el-upload class="importBtn" name="file" action="action" :show-file-list="false" :http-request="fileChange">
                <el-button type="primary" class="daoru">
                    <span class="icon iconfont icon-daoru"></span>
                    导入
                </el-button>
            </el-upload>
            <el-button
              type="primary"
              class="exportBtn"
              @click="exportTeachingPlan"
            >
              <!-- <i class="el-icon-s-promotion"></i> -->
              <span class="icon iconfont icon-daochu"></span>

              导出计划
            </el-button>
          </div>
        </div>
        <div class="tableData">
          <el-table
            ref="multipleTable1"
            :data="tableData"
            tooltip-effect="dark"
            style="width: 100%"
            :header-cell-style="{ textAlign: 'center', background: '#f3f8fc' }"
            :cell-style="cellStyle"
            @selection-change="selectionChange"
          >
            <el-table-column type="selection" width="55"> </el-table-column>
            <el-table-column label="序号" type="index" width="50">
            </el-table-column>
            <el-table-column label="年级" prop="gradeExcelName">
            </el-table-column>
            <el-table-column label="学期" prop="semesterExcelName">
            </el-table-column>
            <el-table-column prop="planName" label="计划名称">
            </el-table-column>
            <el-table-column prop="colleageExcelName" label="所属院校">
            </el-table-column>
            <el-table-column prop="majorExcelName" label="所属专业">
            </el-table-column>
            <el-table-column prop="status" label="发布状态">

              <template slot-scope="scope">
                <el-switch
                  v-model="scope.row.status"
                  active-color="#13ce66"
                  inactive-color="#C2C2C2"
                  active-value="0"
                  inactive-value="1"
                  @change="changeSwitch(scope.row)"
                >
                </el-switch>
              </template>
            </el-table-column>
            <el-table-column label="班级" prop="classExcelName">
            </el-table-column>
            <el-table-column label="所授课程" prop="courseExcelName" >
            </el-table-column>
            <el-table-column label="计划课时" prop="totalLessonPeriod" >
            </el-table-column>
            <el-table-column label="周课时" prop="weekLessonPeriod">
            </el-table-column>
            <el-table-column label="周次" prop="weeks">
            </el-table-column>

            <el-table-column prop="address" label="操作" width="200">
              <template slot-scope="scope">
                <div class="haed">
                  <span @click="curriculumSelect(scope.row)"
                    >课程选择</span>
                    <span class="icon edit" @click="handleEdit(scope.row)">编辑</span>
                    <span class="icon del" @click="handleDelete(scope.row)">删除</span>
                </div>

              </template>
            </el-table-column>
          </el-table>


          
          <!-- 修改弹框 -->
          <div class="editDialog">
            <el-dialog
              :title="addOrEditTitle ? '修改计划' : '添加计划'"
              :visible.sync="editFlag"
              width="700px"
            >
            <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
              <el-form-item label="计划名称：" prop="planName" :validate-event="false">
                <div class="addInput">
                <!-- <p class="planName">计划名称：</p> -->
                <el-input
                  v-model="ruleForm.planName"
                  placeholder="请输入计划名称"
                ></el-input>
              </div>
              </el-form-item>
              <el-form-item label="所属院校：" prop="colleageName">
                <div class="addSelect">
                  <!-- <p class="superiorCollege">所属院校：</p> -->
                  <el-select
                    v-model="ruleForm.colleageExcelName"
                    clearable
                    placeholder="请选择"
                    @clear="infoHandleClear"
                    ref="infoSelectUpResId"
                  >
                    <el-option hidden :value="ruleForm.colleageId" :label="infoUpResName">
                    </el-option>
                    <el-tree
                      :data="editSeletOptions"
                      :props="defaultProps"
                      :expand-on-click-node="false"
                      :check-on-click-node="true"
                      @node-click="infoHandleNodeClick"
                    >
                    </el-tree>
                  </el-select>
                </div>
              </el-form-item>
              <el-form-item label="所属专业：" prop="majorExcelName">
                <div class="addSelect">
                <!-- <p class="superiorCollege">所属专业：</p> -->
                <el-select
                  v-model="ruleForm.majorExcelName"
                  @change="majorSelect"
                  placeholder="请选择所属专业"
                >
                  <el-option
                    v-for="item in editMajorOptions"
                    :key="item.majorId"
                    :label="item.majorName"
                    :value="{value:item.majorId,label:item.majorName}"
                  >
                  </el-option>
                </el-select>
              </div>
              </el-form-item>
              <el-form-item label="年级：" prop="gradeExcelName">
               <div class="addSelect">
                <!-- <p class="superiorCollege">年级：</p> -->
                <el-select
                  v-model="ruleForm.gradeExcelName"
                  @change="changeGrade"
                  placeholder="请选择年级"
                >
                  <el-option
                    v-for="item in gradeOptions"
                    :key="item.typeId"
                    :label="item.typeName"
                    :value="{value:item.typeId,label:item.typeName}"
                  >
                  </el-option>
                </el-select>
                </div>
              </el-form-item>
              <el-form-item label="学期：" prop="semesterExcelName">
                <div class="addInput">
                  <!-- <p class="superiorCollege">学期：</p> -->
                  <el-select
                    v-model="ruleForm.semesterExcelName"
                    @change="semesterChange"
                    placeholder="请选择学期"
                  >
                    <el-option
                      v-for="item in remarkSchoolList"
                      :key="item.id"
                      :label="item.remarkSchool"
                      :value="{value:item.id,label:item.remarkSchool}"
                    >
                    </el-option>
                  </el-select>
                </div>
              </el-form-item>
              <el-form-item label="计划课时：" prop="totalLessonPeriod">
                <div class="addInput">
                  <el-input
                    v-model="ruleForm.totalLessonPeriod"
                    placeholder="请填写计划课时"
                  ></el-input>
                </div>
              </el-form-item>
              <el-form-item label="周课时：" prop="weekLessonPeriod">
                <div class="addInput">
                  <el-input
                    v-model="ruleForm.weekLessonPeriod"
                    placeholder="请填写一周需上课时"
                  ></el-input>
                </div>
              </el-form-item>
              <el-form-item label="周次：" prop="weeks">
                <div class="addInput">
                  <el-input
                    v-model="ruleForm.weeks"
                    placeholder="请填写第几周上课"
                  ></el-input>
                </div>
              </el-form-item>
              <el-form-item label="班级：" prop="classExcelName">
                <div class="addInput">
                  <el-select
                    v-model="ruleForm.classExcelName"
                    @change="classChange"
                    placeholder="请选择所属班级"
                  >
                    <el-option
                      v-for="item in classListData"
                      :key="item.classId"
                      :label="item.className"
                      :value="{value:item.classId,label:item.className}"
                    >
                    </el-option>
                  </el-select>
                </div>
              </el-form-item>
              <el-form-item label="所授课程：" prop="courseExcelName">
                <div class="addInput">
                  <!-- <p class="superiorCollege">学期：</p> -->
                  <el-select
                    v-model="ruleForm.courseExcelName"
                    placeholder="请选择课程"
                    @change="changeCoursesTaught"
                  >
                    <el-option
                      v-for="item in courseData"
                      :key="item.courseId"
                      :label="item.courseName"
                      :value="{value:item.courseId,label:item.courseName}">
                    </el-option>
                  </el-select>
                </div>
              </el-form-item>
              <el-form-item label="授课教师：" prop="teacherExcelName">
                <div class="addInput">
                  <!-- <p class="superiorCollege">学期：</p> -->
                  <el-select
                    v-model="ruleForm.teacherExcelName"
                    @change="teacherChange"
                    placeholder="请选择教师"
                  >
                    <el-option
                      v-for="item in lecturerOptions"
                      :key="item.id"
                      :label="item.teacherName"
                      :value="{value:item.id,label:item.teacherName}">
                    </el-option>
                  </el-select>
                </div>
              </el-form-item>
              <el-form-item label="发布状态：" prop="status">
                <div class="switch">
                  <!-- <p class="superiorCollege">学期：</p> -->
                  <el-switch
                  v-model="ruleForm.status"
                  active-color="#13ce66"
                  inactive-color="#C2C2C2"
                  active-value="0"
                  inactive-value="1"
                  @change="infoChangeSwitch"
                >
                </el-switch>
                </div>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="submitForm('ruleForm')">立即创建</el-button>
                <el-button @click="resetForm('ruleForm')">返回</el-button>
              </el-form-item>
          </el-form>
            </el-dialog>
          </div>

          <!-- 选择课程 -->
          <div class="selectDialog">
            <el-dialog
              title="选择课程"
              :visible.sync="selectClassFlag"
              width="900px"
              height="800px"
            >
              <div class="selectClass">
                <div class="searchClass">
                  <el-input
                    v-model="searchClassValue"
                    placeholder="请输入课程名称"
                    suffix-icon="el-icon-search"
                  ></el-input>
                </div>
              </div>
              <div class="searchClassData">
                <el-table
                  ref="multipleTable"
                  :data="classList"
                  tooltip-effect="dark"
                  style="width: 100%"
                  v-loading = "isLoading"
                  element-loading-text = "加载中，请稍后..."
                  :header-cell-style="{
                    textAlign: 'center',
                    background: '#f3f8fc',
                  }"
                  :cell-style="cellStyle"
                  @select="select"
                >
                  <el-table-column type="selection" width="55">
                  </el-table-column>
                  <el-table-column label="序号" type="index" width="50">
                  </el-table-column>
                  <el-table-column prop="courseName" label="课程名称">
                  </el-table-column>
                  <el-table-column prop="courseTypeName" label="课程类型">
                  </el-table-column>
                  <el-table-column prop="instructionalVersion" label="课程版本">
                  </el-table-column>
                </el-table>
              </div>
              <div class="block" v-show="classList.length">
                <el-pagination
                  @size-change="infoHandleSizeChange"
                  @current-change="infoHandleCurrentChange"
                  :current-page.sync="infoCurrentPage"
                  :page-size="10"
                  prev-text="上一页"
                  next-text="下一页"
                  layout="prev, pager, next, jumper"
                  ref="pagination"
                  :total="infoTotal"
                >
                </el-pagination>
                <el-button class="sure" type="primary">确定</el-button>
              </div>
              <div slot="footer" class="dialog-footer">
                <el-button class="cancel" @click="selectClassCancel"
                  >取 消</el-button
                >
                <el-button
                  class="determine"
                  type="primary"
                  @click="selectClassBtn"
                  >确 定</el-button
                >
              </div>
            </el-dialog>
          </div>
          <div class="block" v-show="tableData.length">
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page.sync="currentPage"
              :page-size="10"
              prev-text="上一页"
              next-text="下一页"
              layout="prev, pager, next, jumper"
              ref="pagination"
              :total="total"
            >
            </el-pagination>
            <el-button class="sure" type="primary" >确定</el-button>
          </div>
        <!-- </div> -->

      </div>
    </div>

  </div>
</template>

<script>
import {
  basicManagementAddApi,
  colleageTreeDataApi,
  majorListApi,
  basicManagementListApi,
  basicManagementRemoveApi,
  batchReleaseApi,
  teachingPlanCourseApi,
  editTeachingPlanApi,
  teachingPlanExportApi,
  getSchoolYearApi,
  getClassGradeListApi,
  getCourseListApi,
  getTeacherListDataApi,
  getGradeListApi,
  addTeachingPlanCourseApi,
  schoolYearItemApi,
  ImportExaminationRoomApi
} from "@/api/basics/teachingPlan.js";
// import {HOST} from "@/global"

export default {
  name: "TeachingPlan",
  data() {
    return {
      seleArr:[],
      // 选择课程table数据
      selectClassData: [],
      // 课程选择value值
      searchClassValue: "",
      // 课程选择开关
      selectClassFlag: false,
      // 院校数据
      collegeOptions: [],
      // 专业数据
      majorOptions: [],
      // 查询院校选择
      collegesValue: "",
      // 查询计划名称
      planNameValue: "",
      // 查询专业
      
      majorValue: "",
      tableData: [], // 表格数据
      multipleSelection: [], // 选中数据
      currentPage: 1, //  显示当前第几页
      infoCurrentPage:1, // 弹框table页码
      editFlag: false, // 修改弹框开关
      editSelectValue: "", // 院校
      editSeletOptions: "", // 院校下拉框
      majorId: "", // 专业
      editMajorOptions: [], // 专业下拉框
      selectId: "", // 选中哪一行id
      addOrEditTitle: false, // 弹框表头
      newArr: [], // 新数组
      ischecks: false,
      spliceItem: [],
      ind: "",
      ids: "", // 选中checked拼接id
      // 树组件
      defaultProps: {
        children: "children",
        label: "label",
      },
      data: [],
      upResName: "", // 院校下拉框
      infoUpResName: "",//  弹框中院校下拉框
      value: "",
      // 树组件选中id
      saveForm: {
        upResId: "",
        upResIds:''
      },
      total:0,  // 管理列表total
      infoTotal:0, // 课程选择弹框分页总条数
      dialogSemester:'',  // 学期
      status:'',  // 发布状态
      selectMajorId: '', // 选择专业id
      selectColleageId:'', // 弹框中学院id
      ruleForm:{
        planName: "", // 计划名称
        colleageId:'',
        majorId:'',
        gradeTypeId:'',
        semesterId:'',
        weekLessonPeriod:'',
        totalLessonPeriod:'',  //  计划课时
        weeks:'',  //  周次
        classId:'',  //  班级
        courseId:'',  //  所授课程
        teacherId:'',  //  授课教师
        status:'1',
        colleageExcelName:'',
        majorExcelName:'',
        gradeExcelName:'',    //年级名
        semesterExcelName:"",   // 学期名
        courseExcelName:'',    //课程名
        classExcelName:'',    //班级名
        teacherExcelName:''    // 教师名
        
      },
      rules: {
          planName: [
            { required: true, message: '请输入计划名称', trigger: 'blur' },
          ],
          colleageId: [
            { required: true, message: '请选择学院', trigger: 'blur' }
          ],
          majorId: [
            {  required: true, message: '请选择专业', trigger: 'blur' }
          ],
          gradeTypeId: [
            { required: true, message: '请选择年级', trigger: 'blur' }
          ],
          semesterId: [
            { required: true, message: '请选择学期', trigger: 'blur' }
          ],
          totalLessonPeriod: [
            { required: true, message: '请填写计划课时', trigger: 'blur' }
          ],
          weeks: [
            { required: true, message: '请填写周次', trigger: 'blur' }
          ],
          weekLessonPeriod: [
            { required: true, message: '请填写一周需上课时', trigger: 'blur' }
          ],
          classId: [
            { required: true, message: '请选择班级', trigger: 'blur' }
          ],
          courseId: [
            { required: true, message: '请选择课程', trigger: 'blur' }
          ],
          teacherId: [
            { required: true, message: '请选择教师', trigger: 'blur' }
          ]
        },
      semesterId:'',  //  学期
      semesterOptions:[],  //  新增学期下拉数据
      weekLessonPeriod:'',  //  周课时
      
      coursesTaughtOptions:[],  //  所授课程下拉数据
      classOptions:[],  //  所授课程
      lecturerOptions:[],  //  授课教师
      classListData:[], // 班级列表名称
      schoolYearList:[], // 学年学期
      gradeOptions:[],  // 年级下拉数据
      courseData:[],  // 课程数据
      planId:'', // 计划id
      bill_id:'', //计划课程选中id
      classList:[], // 所有课程
      isLoading:false, // loading
      filename: "教学计划管理表",
      selectItem:'',
      remarkSchoolList:[],  // 学期数据
      selectIds:''
    };
  },
  // created() {
  //   // table表格
  //   // 查询所属院校下拉框
  //   this.colleageTreeData();
  //   // 新增学院下拉框
  //   this.editSelectTreeData();

  //   // 授课教师
  //   this.getTeacherList()

  //   this.getSchoolYear()

    // this.getMajorIdClass()

  // },
  // created() {
  //   document.getElementsByClassName(
  //     "el-pagination__jump"
  //   )[0].childNodes[0].nodeValue = "跳到第";
  // },
  mounted() {
    this.getCourseList()
    schoolYearItemApi().then(res=>{
      console.log(res,'--------------');
      this.remarkSchoolList = res.data
    })
    this.tableList();
    this.colleageTreeData();
    // 新增学院下拉框
    this.editSelectTreeData();

    // 授课教师
    this.getTeacherList()

    // this.getMajorIdClass()
    this.getSchoolYear()
    document.getElementsByClassName(
      "el-pagination__jump"
    )[0].childNodes[0].nodeValue = "跳到第";

    if(this.selectClassFlag) {
      document.getElementsByClassName(
      "el-pagination__jump"
    )[0].childNodes[0].nodeValue = "跳到第";
    }
    this.getGradeList()
    // getClassGradeListApi().then(res=>{
    //   console.log(res,'-------------->班级');
    // })
    teachingPlanCourseApi().then(res=>{
      console.log(res,'---------------->计划课程数据');

    })
    this.collegesValueHandler()
    // this.select()

  },
  // updated(){
  //   this.toggleSelection(this.classList)
  // },
  watch: {
    // 监听查询学院下拉框
    collegesValue: {
      handler: function (newArr) {
        console.log("obj改变了");
        this.collegesValueHandler(newArr);
      },
      // 开启深度监听：只要obj中的任何一个属性发生改变，都会触发相应的代码
      deep: true,
    },

    // 监听新增学院下拉框
    editSelectValue: {
      handler: function () {
        console.log("obj改变了");
        // this.editSelectValueHandler(newArr);
      },
      // 开启深度监听：只要obj中的任何一个属性发生改变，都会触发相应的代码
      deep: true,
    },
  },
  methods: {
    // 年级列表
    async getGradeList() {
      const data = await getGradeListApi({parentId:55})
      this.gradeOptions = data.rows
      // this.gradeOptions = data.rows.filter(item=>{
      //   return item.status === '0'
      // })
      console.log(data);
    },
     toggleSelection(rows) {
      rows.forEach((row) => {
        [...this.multipleSelection].forEach((it) => {
          if (row.courseId === it.courseId) {
            this.$refs.multipleTable.toggleRowSelection(row, true);
          }
        });
      });
    },
    select(selection,row){
      this.bill_id = row ? row.courseId : "";
      // this.multipleSelection = selection;

      // console.log(row,'----------->row');
      // 清除 所有勾选项
      this.$refs.multipleTable.clearSelection()
      console.log(selection);
      // 当表格数据都没有被勾选的时候 就返回
      // 主要用于将当前勾选的表格状态清除
        
          this.$refs.multipleTable.toggleRowSelection(row, true);
      if(selection.length == 0) return
      // this.selectItem = row
      // let filterItem = selection.filter(item=>{
      //   return item.courseId == row.courseId
      // })
      // if(filterItem.length) {
      // }
      
    },
    // 获取授课教师
    async getTeacherList() {
      const data = await getTeacherListDataApi()
      this.lecturerOptions = data.rows
    },

    // 获取学年学期
    async getSchoolYear() {
      const data = await getSchoolYearApi()
      this.schoolYearList = data.rows

      console.log(data);
    },

    fileChange(files) { 
        let formData = new FormData(); 
        formData.append('file', files.file);
        ImportExaminationRoomApi(formData).then((res) => {
          console.log(res);
          if(res.code === 200) {
            this.$message({
              type: 'success',
              message: '导入成功',
            });
            this.tableList()
          }else {
            this.$message({
              type: 'error',
              message: '导入失败',
            });
          }
        });
    },
    // 根据专业id查询班级
    // async getMajorIdClass(id) {
    //  const data = await getClassGradeListApi({majorId:id})
    //   this.classListData = data.rows
    //   console.log(data,'-------->班级/年级');
    //   // this.getCourseData(id)

    // },

    // 获取授课数据
    async getCourseData(id) {
      const data = await getCourseListApi({majorId:id})
      this.courseData = data.rows
      console.log(data,id,'---------->课程数据');
    },

    // 弹框中状态开关
    infoChangeSwitch(data) {
      console.log(data);
      this.ruleForm.status = data || '1'
    },

    // 导入
    importBtn() {},

    // 选择课程取消
    selectClassCancel() {
      this.selectClassFlag = false
    },
    // 添加弹框取消
    addOrEditCancel() {
      // if(!this.addOrEditTitle){
        this.editFlag = false
        this.planName = ''
        this.infoUpResName = ''
        this.majorId = ''
        this.teacherId = ''

      // }
    },
    submitForm(formName) {
      console.log(this.ruleForm);
        this.$refs[formName].validate((valid) => {
          if (valid) {
              if(!this.addOrEditTitle) {
                basicManagementAddApi(this.ruleForm).then(res=>{
                  if(res.code === 200) {
                    this.$message({
                      type: 'success',
                      message: '添加成功',
                    });
                    this.editSeletOptions = []
                    this.editMajorOptions = []
                    this.gradeOptions = []
                    this.schoolYearList = []
                    this.classListData = []
                    this.courseData = []
                    this.lecturerOptions = []
                  }else {
                    this.$message({
                      type: 'error',
                      message: '添加失败',
                    });
                  }
                  this.tableList();
                  this.editFlag = false
                })
              }else {
                editTeachingPlanApi(this.ruleForm).then(res=>{
                  if(res.code === 200) {
                    this.$message({
                      type: 'success',
                      message: '修改成功',
                    });
                    this.editSeletOptions = []
                    this.editMajorOptions = []
                    this.gradeOptions = []
                    this.schoolYearList = []
                    this.classListData = []
                    this.courseData = []
                    this.lecturerOptions = []
                  }else {
                    this.$message({
                      type: 'error',
                      message: '修改失败',
                    });
                  }
                  this.editFlag = false
                  this.tableList();
                })
              }
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
        this.editFlag = false

      },
    // 批量发布
    batchRelease() {
      console.log(this.ids,'-------------');
      this.$confirm("是否发布？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
              if(this.ids) {
               batchReleaseApi({ids:this.ids}).then(res=>{
                  console.log(res);
                  if(res.code === 200) {
                    this.$message({
                      type: 'success',
                      message: '发布成功',
                    });
                    this.tableList()
                  }
               })

              }else {
                this.$message({
                  type: 'error',
                  message: '请选择发布节点',
                });
              }
          })
          .catch(() => {});


    },
    // select下拉树
    handleNodeClick(data) {
      console.log(data);
      // 这里主要配置树形组件点击节点后，设置选择器的值；自己配置的数据，仅供参考
      this.upResName = data.label;
      this.saveForm.upResId = data.id;
      // 选择器执行完成后，使其失去焦点隐藏下拉框的效果
      this.$refs.selectUpResId.blur();
      this.collegesValueHandler()

    },
    infoHandleClear() {
      // 将选择器的值置空
      this.infoUpResName = "";
      this.colleageId = "";
    },

     // 弹框下拉树
    infoHandleNodeClick(data) {
      // 这里主要配置树形组件点击节点后，设置选择器的值；自己配置的数据，仅供参考
      this.infoUpResName = data.label;
      this.ruleForm.colleageId = data.id;
      // 选择器执行完成后，使其失去焦点隐藏下拉框的效果
      this.$refs.infoSelectUpResId.blur();
      this.ruleForm.colleageExcelName = data.label
      this.editSelectValueHandler(data.id)
      this.majorId = ''
      // this.majorSelect(data.id)

    },
    handleClear() {
    //   // 将选择器的值置空
      this.upResName = "";
      this.ruleForm.colleageId = "";
    },

    // table switch开关
    async changeSwitch(scope) {
      console.log(scope,'------------>');
      const data = await editTeachingPlanApi({status:scope.status,planId:scope.planId})
      console.log(data);
      if(data.code === 200) {
        this.$message({
            type: 'success',
            message: '操作成功',
          });
      }else {
        this.$message({
            type: 'error',
            message: '操作失败',
          });
      }
      this.tableList()
    },

    // 所属院校下拉框
    async colleageTreeData() {
      const data = await colleageTreeDataApi();
      console.log(data, "学院管理左侧导航树");
      this.data = data.data;
    },

    // 所属专业下拉框
    async collegesValueHandler() {
      console.log(this.saveForm.upResId,'=====');
      const data = await majorListApi({ colleageId: this.saveForm.upResId });
      console.log(data);
      this.majorOptions = data.rows;
      // this.editMajorOptions = data.rows;

    },

    // 新增所属学院下拉框
    async editSelectTreeData() {
      const data = await colleageTreeDataApi();
      console.log(data, "学院管理左侧导航树");
      this.editSeletOptions = data.data;
      console.log(data);
    },

    // 新增所属专业下拉框
    async editSelectValueHandler(id) {
      console.log(id,'-----------');
      // console.log(id, "arr");
      const data = await majorListApi({ colleageId: id, status:'0'});
      console.log(data);
      this.editMajorOptions = data.rows;
    },
    // 获取专业id
    majorSelect(obj) {
      // this.changeGrade(id)
      this.getCourseData(obj.value)
      // this.classId = ''
      getClassGradeListApi({majorId:obj.value,status:'0'}).then(res=>{
        console.log(res,'------->获取班级');
        this.classListData = res.rows
        // this.classListData = res.rows.filter(item=>{
        //   return item.status == '0'
        // })
      })
      this.ruleForm.majorExcelName = obj.label
      this.ruleForm.majorId = obj.value
      teachingPlanCourseApi({majorId:obj.value}).then(res=>{
        console.log(res,'---------------->计划课程数据');
        this.coursesTaughtOptions = res.rows
      })

    },

    // 年级
    changeGrade(obj) {
      // this.getMajorIdClass(id)
      console.log(obj);
      this.gradeTypeId = obj.value
      this.ruleForm.gradeExcelName = obj.label

      // console.log(id,'------------>年级id');
    },
    // 学年学期
    semesterChange(obj) {
      this.ruleForm.semesterExcelName = obj.label
    },
    classChange(obj) {
      console.log(obj);
      this.ruleForm.classExcelName = obj.label
    },
    // 重置按钮
    refreshBtn() {
      this.planNameValue = "";
      this.majorValue = "";
      this.upResName = "";
      this.saveForm.upResId = ''
      this.majorOptions = []
      this.tableList();
    },
    // 添加学院
    addCollege() {
      // this.$refs['ruleForm'].resetFields();
      this.ruleForm = {}

      this.editFlag = true;
      this.addOrEditTitle = false;
      // this.planName = ''
      // this.colleageId = ''
      // this.majorId = ''
      this.ruleForm.colleageId
      this.infoUpResName = '';
      // this.colleageId = ''
      // this.classId = ''
      // this.courseId = ''
      // this.weekLessonPeriod = '',
      // this.weeks = ''
      // this.totalLessonPeriod = ''
      // this.classListData = []
      // this.editMajorOptions = []
      // this.classListData = []
      // this.courseData = []
      // this.gradeTypeId = ''
      // this.semesterId = ''
      // this.teacherId = ''
      this.editSelectTreeData()
      this.getGradeList()
      this.getTeacherList()
      this.getSchoolYear()
    },

    // 导出
    exportTeachingPlan() {
        this.$confirm("是否导出全部数据？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
              teachingPlanExportApi().then((res)=>{
                console.log(res)
                if (!res) return;
                const blob = new Blob([res], {
                  type: "application/vnd.ms-excel",
                }); // 构造一个blob对象来处理数据，并设置文件类型
                if (window.navigator.msSaveOrOpenBlob) {
                  //兼容IE10
                  navigator.msSaveBlob(blob, this.filename);
                } else {
                  const href = URL.createObjectURL(blob); //创建新的URL表示指定的blob对象
                  const a = document.createElement("a"); //创建a标签
                  a.style.display = "none";
                  a.href = href; // 指定下载链接
                  a.download = this.filename; //指定下载文件名
                  console.log(this.filename);
                  a.click(); //触发下载
                  URL.revokeObjectURL(a.href); //释放URL对象
                }
              })
              // const a = document.createElement("a"); //创建a标签
              // a.href = `${HOST}/common/download?fileName=${res.msg}`; // 指定下载链接
              // a.click(); //触发下载
          })
          .catch(() => {});
    },

    // 选择课程确定按钮
    selectClassBtn() {
      console.log(this.bill_id,'--------------->classList');
      teachingPlanCourseApi({teachingPlanId:this.planId}).then(res=>{
        console.log(res);
        if(res.code === 200) {
          if(res.rows.length > 0) {
            this.$message({
              type: 'error',
              message: '该计划已有课程',
            });
          }else {
            addTeachingPlanCourseApi({teachingPlanId:this.planId,ids:this.bill_id}).then(res=>{
              console.log(res);
              if(res.code === 200) {
                this.$message({
                  type: 'success',
                  message: '操作成功',
                });
                this.tableList()
                this.selectClassFlag = false;
              }else {
                this.$message({
                  type: 'error',
                  message: '操作失败',
                });
              }
            })
          }
        }
      })
      
    },
    // 修改/添加  确定事件
    async editBtn() {
      console.log(this.classId,'ppp');
      if (!this.addOrEditTitle) {
        let data = {
          planName: this.planName,
          colleageId: this.colleageId || this.selectColleageId,
          majorId: this.majorId,
          status:this.status,
          classId:this.classId,
          totalLessonPeriod:this.totalLessonPeriod,
          weekLessonPeriod:this.weekLessonPeriod,
          weeks:this.weeks,
          gradeTypeId:this.gradeTypeId,
          semesterId:this.semesterId,
          courseId:this.courseId,
          teacherId:this.teacherId
        };
        console.log(this.ruleForm);
        // if(
        //   data.planName &&
        //   data.colleageId &&
        //   data.majorId &&
        //   data.classId &&
        //   data.totalLessonPeriod &&
        //   data.weeks
        // ) {
          const res = await basicManagementAddApi(data);
          if(res.code === 200) {
            this.$message({
              type: 'success',
              message: '添加成功',
            });
            this.editSeletOptions = []
            this.editMajorOptions = []
            this.gradeOptions = []
            this.schoolYearList = []
            this.classListData = []
            this.courseData = []
            this.lecturerOptions = []
          }else {
            this.$message({
              type: 'error',
              message: '添加失败',
            });
          }
          this.tableList();
        // }
        // else {
        //   this.$message({
        //     type: 'error',
        //     message: '请填写完整信息',
        //   });
        // }

      }else {
        let obj = {
          planName: this.editInputValue,
          colleageId: this.colleageId || this.selectColleageId,
          majorId: this.majorId,
          status:this.status,
          classId:this.classId,
          totalLessonPeriod:this.totalLessonPeriod,
          weekLessonPeriod:this.weekLessonPeriod,
          weeks:this.weeks,
          gradeTypeId:this.gradeTypeId,
          semesterId:this.semesterId,
          courseId:this.courseId,
          teacherId:this.teacherId,
          planId:this.selectId
        }
        console.log(this.selectMajorId);
        const data = await editTeachingPlanApi(obj)
        this.tableList();
        console.log(data,'修改教学计划');
      }
      this.editFlag = false;

    },
    // table 表格数据
    async tableList() {
      const data = await basicManagementListApi({pageSize:'10',pageNum:this.currentPage});
      if (data.code === 200) {
        console.log(data, "table");
        this.tableData = data.rows;
        this.total = data.total
      }else {
        this.$message.error('数据请求失败，请稍后重试', data.msg);
      }
    },
    getCourseList() {
      getCourseListApi({pageSize:'10',pageNum:this.infoCurrentPage}).then(res=>{
        console.log(res);
        this.classList = res.rows
        this.infoTotal = res.total
        this.tableList()
      })
    },
    // 选择课程事件
    async curriculumSelect(row) {
      this.selectClassFlag = true;
      console.log(row);
      this.$nextTick(()=>{
        document.getElementsByClassName(
          "el-pagination__jump"
        )[0].childNodes[0].nodeValue = "跳到第";
      })
      console.log(this.$refs.multipleTable);
      this.$nextTick(()=>{
        this.$refs.multipleTable.clearSelection()
      })

      // this.multipleSelection = []
      // console.log(this.multipleSelection);
      teachingPlanCourseApi({teachingPlanId:row.planId}).then(res=>{
        console.log(res.rows);
        this.selectList = res.rows
        this.multipleSelection = res.rows
        console.log(this.multipleSelection);
          this.$nextTick(()=>{
        this.toggleSelection(this.classList)
      })
      })
    
      // this.$nextTick(()=>{
      //    if(this.selectList.length) {
      //      this.$refs.multipleTable.toggleRowSelection(this.selectList[0], true);
      //    }
      // })
      console.log(row,'-----------------');
      this.selectIds = row.planId
      console.log(this.selectItem);
      console.log(row,'-------rowsss');
      this.isLoading = true
      // const data = await teachingPlanCourseApi({teachingPlanId:row.planId,pageSize:'10',pageNum:this.infoCurrentPage})
        // console.log(data);

      // if(data.code === 200) {
        this.isLoading = false
      //   // this.classList = data.rows
      // }
      //   this.infoTotal = res.total
      // })
      this.planId = row.planId
      // this.selectClassData = data.rows
      console.log(row,'---------rrrr');
      // console.log(data,'---------data');
    },
    // 分页  事件
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.tableList()
    },
    // 分页  事件
    infoHandleSizeChange(val) {
      console.log(`每页 ${val} 条`);
    },
    infoHandleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      // this.tableList()
      this.getCourseList()
    },
    changeCoursesTaught(obj) {
      this.ruleForm.courseId = obj.value
      this.ruleForm.courseExcelName = obj.label
    },
    teacherChange(obj) {
      console.log(obj);
      this.ruleForm.teacherExcelName = obj.label
    },
    // table  事件  修改
    handleEdit(row) {
      console.log(row);
      console.log(this.majorId);
      this.ruleForm = row
      delete this.ruleForm.courseName
      this.infoUpResName = row.colleageName
      console.log(this.ruleForm,'-0000000');
      this.addOrEditTitle = true;
      this.editFlag = true;
      this.majorSelect(row.majorName)
      this.editSelectValueHandler(row.colleageId)
      this.getTeacherList()
      this.getSchoolYear()
      this.getGradeList()
      this.colleageTreeData()
      this.collegesValueHandler()
      // this.majorSelect()
    },
    // 表格选中事件
    selectionChange(val) {
      console.log(val);
      var arrTostring = [];
      val.forEach((item) => {
        if (arrTostring.indexOf(item.id) === -1) {
          arrTostring.push(item.planId);
        }
      });
      this.checkedList = val
      this.ids = arrTostring.toString();
    },
    // 删除按钮
    handleDelete(index) {
      console.log(index);
      this.$confirm("确认删除记录吗?", "提示", {
        type: "warning",
      }).then(() => {
        console.log(this.ids);
        basicManagementRemoveApi({ ids: index.planId }).then(res=>{
          if(res.code === 200) {
            this.$message({
              type: 'success',
              message: '删除成功'
            });
            this.tableList();
          }else {
            this.$message({
              type: 'error',
              message: '删除失败'
            });
          }
        });
      });
    },
    // 设置table样式
    cellStyle(row) {
      let { columnIndex } = row;
      if (columnIndex === 6) {
        //指定坐标rowIndex ：行，columnIndex ：列
        return {  textAlign: "center" }; //rgb(105,0,7)
      } else {
        return { textAlign: "center" };
      }
    },
    // 搜索按钮
    async searchBtn() {
      // 判断计划名称不能为空
        const data = await basicManagementListApi({
          planName: this.planNameValue,
          colleageId: this.saveForm.upResId,
          majorId: this.majorValue,
        });
        this.tableData = data.rows
    },
    // 批量删除
    moreDelete() {
      console.log(this.multipleSelection, "ppp");
      this.$confirm("确认删除记录吗?", "提示", {
        type: "warning",
      }).then(() => {
        console.log(this.ids);
        basicManagementRemoveApi({ ids: this.ids }).then(res=>{
          if(res.code === 500) {
            this.$message({
              type: 'error',
              message: '删除失败，请检查是否有选择计划',
            });
          }else {
            this.tableList();
            this.$message({
              type: 'success',
              message: '删除成功',
            });

          }
        });
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.TeachingPlan {
  min-width: 100vh;
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  padding: 0 20px 20px;
  background-color: rgb(242, 241, 246);
  display: flex;
  flex-direction: column;

  .editDialog {
    ::v-deep .el-dialog {
      width: 700px;
      // height: 740px;
      border-radius: 10px;
      font-weight: 600;
      .el-dialog__header {
        border-radius: 10px 10px 0 0;
        text-align: center;
        background-color: rgb(72, 149, 219);
        .el-dialog__title {
          color: #fff;
        }
        .el-dialog__headerbtn .el-dialog__close {
          color: #fff;
        }
      }
      .el-form-item {
        display: flex;
        justify-content: center;
        .el-form-item__content{
          margin-left: 0 !important;
        }
      }
      .addInput {
        display: flex;
        justify-content: center;
        align-items: center;
        margin-bottom: 10px;
        // justify-content: space-around;
        .planName,.superiorCollege {
          text-align: right;
          width: 70px;
        }
        .el-input {
          width: 300px;
        }
      }
      .switch{
        width: 300px;
      }
      .state {
        width: 100%;
        display: flex;
        .infoState{
          text-align: right;
          width: 217px;
        }

      }
      .addSelect {
        display: flex;
        justify-content: center;
        align-items: center;
        margin-bottom: 10px;

        .superiorCollege {
          width: 70px;
          text-align: right;
        }
        .el-select {
          width: 300px;
        }
      }
      // .el-dialog__body {
      //   // height: 600px;
      // }
      .dialog-footer {
        text-align: center;
        button {
          width: 100px;
          height: 35px;
          border-radius: 16px;
          line-height: 0;
        }
        .cancel {
          border: none;
          color: #848383;
          background-color: #f0f0f0;
        }
        .determine {
          border: none;
          background-color: #4995dc;
        }
      }
    }
  }
  .selectDialog {
    border-radius: 10px;
    font-weight: 600;

    .selectClass {
      width: 300px;
      float: right;
      margin-bottom: 10px;
    }

    ::v-deep .el-dialog {
      border-radius: 10px;
      height: 830px;
    }

    ::v-deep .el-dialog__header {
      border-radius: 10px 10px 0 0;
      text-align: center;
      background-color: rgb(72, 149, 219);
      .el-dialog__title {
        color: #fff;
      }
      .el-dialog__headerbtn .el-dialog__close {
        color: #fff;
      }
    }
    ::v-deep .el-dialog .el-dialog__body {
      height: 680px;
      .el-table__header-wrapper .el-checkbox {
        display: none;
      }
    }
    .dialog-footer {
      // height: 100%;
      text-align: center;
      button {
        width: 100px;
        height: 35px;
        border-radius: 16px;
        line-height: 0;
      }
      .cancel {
        border: none;
        color: #848383;
        background-color: #f0f0f0;
      }
      .determine {
        border: none;
        background-color: #4995dc;
      }
    }
  }
  .TeachingPlanTop {
        min-width: 100vh;
        width: 100%;
        // height: 100px;
        display: flex;
        font-size: 14px;
        // justify-content: space-between;
        align-items: center;
        background: #fff;
        flex-wrap: wrap;
        border-radius: 10px;
        padding: 0 20px;
        box-shadow: 0px 4px 3px #ccc;

        .planName,
        .school,
        .major {
            display: flex;
            flex-wrap: nowrap;
            text-align: center;
            align-items: center;
            width: 270px;
            margin: 20px 0;
            p {
                text-align: right;
                width: 112px;
            }
            .el-input{
                width: 170px;
            }
        }
        .moreBtn {
        width: 200px;
        margin: 10px 10px;
        display: flex;
        .searchBtn {
            color: white;
            border: none;
            background-color: rgb(123, 180, 208);
        }
        .refreshBtn {
            color: white;
            border: none;
            background-color: rgb(108, 207, 204);
        }
        }
    }
  .TeachingPlanBottom {
    width: 100%;
    flex: 1;
    background-color: white;
    padding: 0 20px;
    margin-top: 10px;
    border-radius: 10px;
    box-sizing: border-box;
    // .infoTeachingPlanBottom {
      width: 100%;
      height: 100%;
      .operationBtns {
        width: 100%;
        height: 60px;
        display: flex;
        align-items: center;
        margin-top: 10px;
        justify-content: space-between;
        .setBtnsLeftTitle {
          width: 200px;
          font-size: 16px;
          font-weight: 600;
          color: rgb(57, 141, 220);
          p {
            width: 100px;
          }
        }
        .setBtns {
          width: 600px;
          display: flex;
          justify-content: right;
          button {
            border: none;
          }
          .newAdd {
            background-color: rgb(86, 164, 212);
          }
          .moreDelete {
            background-color: rgb(241, 129, 143);
          }
          .moreRelease {
            text-align: center;
            background-color: rgb(127, 162, 216);
            .shareImg {
              width: 15px;
              height: 15px;
              margin-top: -3px;
              background: #fff;
            }
            ::v-deep .el-icon-s-promotion {
              color: white;
            }
          }
          .importBtn{
            background-color: #66c8e3;
            margin: 0 10px;
            border-radius: 5px;
            .el-button {
              background-color: #66c8e3;
            }
          }
          .exportBtn {
            background-color: #fabd90;
          }
        }
      }
    // }
    .tableData {
      width: 100%;
      overflow-y: auto;
      .haed {
        cursor: pointer;
        align-items: center;
        color: #1990FF;

        .setPlan{
          margin-left: 10px;
        }
      }

      ::v-deep .el-table thead tr {
        background-color: #f2f8fb !important;
      }
      ::v-deep .el-table tr:nth-child(2n) {
        background-color: #f9f9f9;
      }
      .edit {
        width: 15px;
        height: 15px;
        margin-left: 10px;
        cursor: pointer;
        color: #1990FF;
      }
      .del {
        width: 15px;
        height: 15px;
        margin-left: 10px;
        color: #1990FF;
        // font-weight: bold;
        cursor: pointer;
      }
      ::v-deep .el-checkbox__input.is-checked .el-checkbox__inner,
      .el-checkbox__input.is-indeterminate .el-checkbox__inner {
        background-color: #86caf0;
        border-color: #86caf0;
      }

      ::v-deep .el-checkbox__input.is-indeterminate .el-checkbox__inner {
        background-color: #86caf0;
        border-color: #86caf0;
      }
      .el-icon-delete {
        color: red;
        font-weight: bold;
        margin-left: 15px;
        font-size: 18px;
      }
      .el-icon-edit-outline {
        font-size: 18px;
        font-weight: bold;
        color: rgb(142, 198, 216);
      }
      .share {
        margin-left: 15px;
      }
      ::v-deep .el-checkbox__input .is-checked .el-checkbox__inner {
        background: red !important;
      }
    }
  }
  .block {
    padding: 0 20px 0 0;
    height: 65px;
    display: flex;
    align-items: center;
    justify-content: right;
    background-color: #fff;

    ::v-deep .btn-prev {
      border: solid 1px #e6e6e6;
      border-radius: 5px;
      color: #6f6f6f;
    }

    ::v-deep .btn-next {
      border: solid 1px #e6e6e6;
      border-radius: 5px;
      color: #6f6f6f;
    }
    ::v-deep .el-pager li {
      background: #fff;
      font-size: 13px;
      min-width: 30.5px;
      height: 28px;
      line-height: 28px;
      box-sizing: border-box;
    }

    ::v-deep .el-pager li.active {
      background-color: #4895db;
      color: #fff;
      cursor: default;
    }
    ::v-deep .number {
      border: solid 1px #e6e6e6;
      margin: 0 5px;
      border-radius: 5px;
      color: #6f6f6f;
    }
    ::v-deep .el-button {
      // width: 50px;
      height: 28px;
      line-height: 0;
    }
    .sure {
      width: 50px;
      height: 30px;
      line-height: 0;
      text-align: center;
      padding: 0;
    }
  }
}
</style>